package com.lambkit.core;

import cn.hutool.log.Log;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author yangyong(孤竹行)
 */
public abstract class CronExecutor {
    private final static Log log = Log.get(CronExecutor.class);


    private final ScheduledExecutorService executorService;
    /**
     * 心跳开关的状态
     */
    private volatile boolean currentStatus = true;
    /**
     * 心跳周期，2秒
     */
    private long heartBeatCircle = 200;
    /**
     * 初始化完成后延迟多长时间执行第一次任务
     */
    private long heartBeatDelay = heartBeatCircle;

    public CronExecutor(long heartBeatCircle, boolean currentStatus) {
        executorService = Executors.newSingleThreadScheduledExecutor();
        this.currentStatus = currentStatus;
        this.heartBeatCircle = heartBeatCircle;
    }

    public static CronExecutor create(long heartBeatCircle, boolean currentStatus, Runnable runnable)  {
        return new CronExecutor(heartBeatCircle, currentStatus) {
            @Override
            public void execute() {
                runnable.run();
            }
        };
    }

    public abstract void execute();

    public void start() {
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // 开关为开启状态，则执行
                if (isHeartbeatOpen()) {
                    execute();
                }
            }
        }, heartBeatDelay, heartBeatCircle, TimeUnit.MILLISECONDS);
    }

    public void close() {
        executorService.shutdown();
        log.info("CronExecutor closed.");
    }

    // 检查心跳开关是否打开
    private boolean isHeartbeatOpen() {
        return currentStatus;
    }

    public void setHeartbeatOpen(boolean open) {
        currentStatus = open;
    }
}
